package com.lxlg.lxlg_order.app.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxlg.lxlg_order.alipay.config.AlipayConfig;
import com.lxlg.lxlg_order.common.constvalue.AllOrderConstValue;
import com.lxlg.lxlg_order.infra.mapper.GoodsOrderMapper;
import com.lxlg.lxlg_order.infra.mapper.RechargeVipMapper;
import com.lxlg.lxlg_order.infra.mapper.SeckillOrderMapper;
import com.lxlg.lxlg_order.infra.model.GoodsOrder;
import com.lxlg.lxlg_order.infra.model.RechargeVip;
import com.lxlg.lxlg_order.infra.model.SeckillOrder;
import com.lxlg.lxlg_order.service.service.GoodsOrderService;
import com.lxlg.lxlg_order.service.service.RechargeVipService;
import com.lxlg.lxlg_order.service.service.SeckillOrderService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static java.lang.System.out;
@RequestMapping("allOrderPayBack")
@RestController
public class OrderPayback {

    @Resource
    private RechargeVipService rechargeVipService;
    @Resource
    private GoodsOrderService goodsOrderService;
    @Resource
    private SeckillOrderService seckillOrderService;

    @Resource
    private SeckillOrderMapper seckillOrderMapper;
    @Resource
    private GoodsOrderMapper goodsOrderMapper;
    @Resource
    private RechargeVipMapper rechargeVipMapper;

    @SneakyThrows
    @PostMapping("payBack.do")
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        out.println("我进入回调");
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = req.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //		valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

   /* 实际验证过程建议商户务必添加以下校验：
   1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
   2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
   3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
   4、验证app_id是否为该商户本身。
   */
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(req.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//            //订单类型
//            Integer orderTyep=Integer.parseInt(req.getParameter("order_type"));
            //支付宝交易号
            String trade_no = new String(req.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(req.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知


                //1删除redis 中的票
                // 修改mybatis中的票的状态
                //4修改电影票房
                //2修改订单状态
                //3生成取票码
                //5日志修改
                Integer orderTyep=null;
                QueryWrapper<SeckillOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("seckill_order_code",out_trade_no);
                SeckillOrder seckillOrder = seckillOrderMapper.selectOne(queryWrapper);
                if(null!=seckillOrder){
                    orderTyep=AllOrderConstValue.order_type_recharge;
                }

                QueryWrapper<GoodsOrder> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("order_code",out_trade_no);
                goodsOrderMapper.selectOne(queryWrapper1);
                if(null!=seckillOrder){
                    orderTyep=AllOrderConstValue.order_type_form;
                }
                QueryWrapper<RechargeVip> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("recharge_order_code",out_trade_no);
                rechargeVipMapper.selectOne(queryWrapper2);
                out.println(out_trade_no);
                out.println("准备回调修改状态");

                String substring = out_trade_no.charAt(0)+"";
                if(substring.equals("s")){
                    seckillOrderService.seckillorderPayBack(out_trade_no);
                }else if (substring.equals("r")){
                    rechargeVipService.rechargerPayBack(out_trade_no);
                }else{
//                    substring.equals("n")
                    goodsOrderService.formorderPayBack(out_trade_no);
                }
            }
            out.println("success");

        } else {//验证失败
            out.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

}

